<template>
    <el-container>
        <el-main>
            <el-form status-icon :model="form" ref="form" :rules="rules" label-position="'left'" >
                <el-form-item label="邮箱" prop="email">
                    <el-input prefix-icon="el-icon-user-solid"  v-model.trim="form.email" placeholder="输入邮箱" :disabled="btn_disable" ></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password" >
                    <el-input prefix-icon="el-icon-lock"  v-model.trim="form.password" placeholder="输入密码" type="password" ></el-input>
                </el-form-item>

                <el-form-item label="姓名" prop="name" >
                    <el-input prefix-icon="el-icon-lock"  v-model.trim="form.name" placeholder="输入姓名" type="text" ></el-input>
                </el-form-item>

                <el-form-item label="性别" prop="sex" >
                    <el-select v-model="form.sex" placeholder="选择性别">
                        <el-option label="男" :value="'男'"></el-option>
                        <el-option label="女"  :value="'女'"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="验证码" prop="ver_code">
                    <el-input prefix-icon="el-icon-lock"  v-model.trim="form.ver_code" placeholder="输入验证码" style="width: 200px"
                    ></el-input>
                    <div style="float: right">
                        <el-button type="primary" style="width: 100px;" @click="getLoginVerCode" :disabled="btn_disable" >获取验证码</el-button>
                    </div>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="onRegister">注册</el-button>
                    <el-button @click="$emit('iclose')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-main>
    </el-container>
</template>

<script>
    import http from "../utils/req";
    import {ElMessage} from "element-plus/es";


    let emailAttr = 'email_code_time'
    let usage = 'register'
    let emailRegisterAttr =  emailAttr + usage
    let email = 'email' + usage
    export default {
        name: "Register",
        props: ['showLogin'],
        event: ['myClose'],
        data(){
            return{
                form: {
                    email: '',
                    password: '',
                    name: '',
                    sex: '',
                    ver_code: ''
                },
                rules:{
                    email: [{required: true,  message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    name: [{required: true, message: '请输入姓名', trigger: 'blur'},
                        {max: 10, message: '姓名长度最大为10', trigger: ['blur', 'change']}
                    ],
                    password: [{required: true, message: '请输入密码', trigger: 'blur'}, ],
                    ver_code: [{required: true, message: '请输入验证码', trigger: 'blur'},
                        { min: 6, max: 6, message: '长度为6个字符', trigger: 'blur' }]
                },
                btn_disable: false,
                timer: null
            };
        },
        methods: {
            onRegister: function(){
                this.$refs['form'].validate((valid) => {  // 校验数据
                    if (valid) {
                        http.postDataWithSymEnc('/auth/register', this.form).then(res=>{
                            if (res.data.code === 200){
                                sessionStorage.removeItem(emailRegisterAttr);
                                sessionStorage.removeItem(email)
                                ElMessage.success({
                                    message: res.data.msg,
                                    type: 'success',
                                    zIndex: -1
                                });
                                this.$emit('iclose', true);
                            }else{
                                ElMessage.warning({
                                    message: res.data.msg,
                                    type: 'warning',
                                    zIndex: -1
                                });
                            }
                        }).catch(reason => {
                            ElMessage.warning({
                                message:reason.message,
                                type: 'warning',
                                zIndex: -1
                            });
                        })
                    }
                });
            },
            getLoginVerCode: function () {
                if (this.btn_disable){
                    return false;
                }
                this.$refs['form'].validateField('email', (err)=>{
                    if (!err){
                        clearInterval(this.timer)
                        this.disableBtn(false);
                        sessionStorage.setItem(email, this.form.email)
                        http.get("/auth/email_code", {params: {email: this.form.email, usage: usage}}).then((res)=>{
                            if (res.data.code ===200){
                                ElMessage.success({
                                    message: res.data.msg,
                                    type: 'success',
                                    zIndex: -1
                                });
                                this.disableBtn(true);
                            }else{
                                ElMessage.warning({
                                    message: res.data.msg,
                                    type: 'warning',
                                    zIndex: -1
                                });
                                this.timer = setInterval(this.tryEnableBtn, 1000); // 启动定时刷新按钮状态
                            }
                        }).catch((reason => {
                            this.timer = setInterval(this.tryEnableBtn, 1000); // 启动定时刷新按钮状态
                        }))
                    }
                })
            },
            tryEnableBtn: function(){
                if (!this.form.email || this.form.email ==='') {
                    this.form.email = sessionStorage.getItem(email);
                }
                if (this.btn_disable){
                    let expireTime = parseInt(sessionStorage.getItem(emailRegisterAttr));
                    if (!expireTime || Date.now() >= expireTime){
                        this.btn_disable = false;
                        sessionStorage.removeItem(emailRegisterAttr);
                        sessionStorage.removeItem(email)
                    }
                }
            },
            disableBtn: function (setExpire = true) {
                this.btn_disable = true;
                if (setExpire){
                    let expireTime = Date.now() + 120 * 1000;
                    sessionStorage.setItem(emailRegisterAttr, expireTime.toString());
                }
            }
        },
        mounted(){
            this.disableBtn(false)
            this.tryEnableBtn();  // 尝试使能获取验证码
            this.timer = setInterval(this.tryEnableBtn, 1000); // 启动定时刷新按钮状态
        }
    }
</script>

<style scoped>
    .el-main{
        min-height: 300px;
    }
</style>